package com.qf.java2201.dao.impl;

import com.qf.java2201.dao.UserDao;
import com.qf.java2201.pojo.HUser;
import com.qf.java2201.pojo.HUserinfo;
import com.qf.java2201.utils.DbUtils1;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigInteger;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    QueryRunner query = new QueryRunner(DbUtils1.getDs());
    @Override
    public HUser login(HUser huser) {


        String sql = "select * from h_user where uname = ? and upwd =  ? ";

        HUser update = null;
        try {
            update = query.query(sql,new BeanHandler<>(HUser.class), huser.getUname(), huser.getUpwd());

            if (update != null) {
                //因为在页面  要展示 用户的真实姓名 所以 这里要把真实姓名等信息查询出来
                String sql1 = "select * from h_userinfo where uuid = ?";

                HUserinfo hUserinfo = query.query(sql1, new BeanHandler<>(HUserinfo.class), update.getUuid());

                update.setUi(hUserinfo);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        System.out.println(sql);
        return update;
    }

    @Override
    public int register(HUser hUser) {

        //注册用户信息  需要存入 h_user表 和 h_userinfo表
        DbUtils1.begin(); //开启事务

        //解助第三方工具类

        String sql = "insert into h_user values (null, ?, ?, ?)";

        int update1 = 0;
        try {
          int  update = query.update(DbUtils1.getConnection(), sql, hUser.getUname(), hUser.getUpwd(), hUser.getRid());

          //查询刚才 插入的那条记录的  主键值
          String sql1 = "select LAST_INSERT_ID()";

          //查询刚刚插入的那条记录 主键值 是一个 数值  所以这里用ScalarHandler

            BigInteger lastId = query.query(DbUtils1.getConnection(), sql1, new ScalarHandler<BigInteger>());

            //用户详情信息 对象
            HUserinfo ui = hUser.getUi();
            ui.setUuid(lastId.intValue());

            String sql2 = "insert into h_userinfo (did, drealname, dage, dsex, uuid, dphone, didcard, demail,dqq) " + "values (null, ?, ?, ?, ?, ?, ?, ?, ?)";

             update1 = query.update(DbUtils1.getConnection(), sql2, ui.getDrealname(), ui.getDage(), ui.getDsex(), ui.getUuid(), ui.getDphone(), ui.getDidcard(), ui.getDemail(), ui.getDqq());

            DbUtils1.commit(); //提交

        } catch (Exception throwables) {
            DbUtils1.rollback();
            throwables.printStackTrace();
        }
        return update1;
    }
}
